/*
 * 用于 Zhihu Android WebView Editor
 *
 * 依赖:
 * zepto.min.js
 * lazyload.js
 * image.js
 * caret.js
 * template.js
 * link-box.js
 * video-box.js
 * wrapper.js
 *
 * native 需要实现的接口有:
 * void onClickBody();
 * void onDocumentReady();
 * void onHtmlGenerated(String html);
 * void onMentionKeyUp();
 * void onTextChanged(int length);
 * String provideContent();
 * String providePlaceholder();
 * String provideSharePostHtml();
 * boolean isSharePostHolderVisible();
 * int provideContentHeight();
 * int provideContentPaddingTop();
 * int provideContentPaddingBottom();
 * int provideContentPaddingLeft();
 * int provideContentPaddingRight();
 *
 * native 可以调用的方法有:
 * void appendMention(long id, String name);
 * void generateHtml();
 * void requestEditorFocus();
 * void startIntervalSave();
 * void stopIntervalSave();
 * void insertImage(int id, String url);
 * void updateImage(int id, String url, int width, int height);
 * void removeImage(int id);
 * void setPlaceholder(String placeholder);
 * void setContentHeight(int height);
 * void setContentVisible(boolean visible);

 */

function appendMention(id, name) {
	if (isAt()) {
		document.execCommand('Delete', 'false', null);
	}

	var mentionHtml = '&nbsp;<a data-hash="' + id + '" href="/people/' + id + '" class="member_mention">@' + name + '</a>&nbsp;'
	document.execCommand('insertHTML', false, mentionHtml);
}

function generateHtml() {
	var editor = $('#editor').clone();

	$('img', editor).each(function() {
		var image = $(this);
		var src = image.attr('original-src');
		image.removeAttr('original-src');
		image.attr('src', src);
	});

	EditorBridge.onHtmlGenerated(html);
}

function requestEditorFocus() {
	$('#editor').focus();
}

// 每隔 10 秒自动保存一次
var intervalId = 0;
function startIntervalSave() {
	stopIntervalSave();
	intervalId = setInterval("generateHtml()", 10000);
}
function stopIntervalSave() {
	clearInterval(intervalId);
}

function insertImage(id, url) {
	var sel;
	var html = '<img src="' + url + '" id="' + id + '"><div>';
	if (document.queryCommandSupported("insertHTML")) {
		document.execCommand("insertHTML", false, html);
	} else if ((sel = document.selection) && sel.type != 'Control') {
		var range = sel.createRange();
		range.pasteHTML(imgHtml);
		range.collapse(false);
		range.select();
	}
}

function updateImage(id, url, width, height) {
	var image = $('#' + id);
	image.attr('original-src', url);
	image.attr('data-rawwidth', width);
	image.attr('data-rawheight', height);
	image.attr('width', width);
	image.removeAttr('id');
}

function removeImage(id) {
	$('#' + id).remove();
}

function setPlaceholder(placeholder) {
	$('#editor').attr('placeholder', placeholder);
}

function setContentHeight(height) {
	$('#editor').css('min-height', height + 'px');
}

function setContentVisible(visible) {
	if (visible) {
		$('#editor').css('visibility', 'visible');
	} else {
		$('#editor').css('visibility', 'hidden');
	}
}


// =================================================================================================

function isAt() {
	var selText = window.getSelection().anchorNode.textContent.substring(0, window.getSelection().anchorOffset);
	if (selText.length > 0) {
		var lastChar = selText.substr(selText.length - 1);
		return lastChar == '@';
	}

	return false;
}

// 保证 backspace 可以正常删除链接
function reformatLinks() {
	$('a').children('span').each(function() {
		var that = $(this);
		var content = that.html();
		that.replaceWith(content);
	});
}

var beforeLength = -1;
function setupEditor() {
	var editor = $('#editor');

	editor.keydown(function() {
		beforeLength = getCaretOffset(editor[0]);
	});

	editor.keyup(function() {
		var afterLength = getCaretOffset(editor[0]);
		EditorBridge.onTextChanged(afterLength);
		if (afterLength > beforeLength && isAt()) {
			EditorBridge.onMentionKeyUp();
		}
	});

	// paste 回调只会获取粘贴之前的光标位置，需要自己手动加上粘贴文本的长度
	editor.on('paste', function(e) {
		var text = (e.originalEvent || e).clipboardData.getData('text/plain');
		var afterLength = getCaretOffset(editor[0]) + text.length;
		EditorBridge.onTextChanged(afterLength);
	});
}

// =================================================================================================

var paddingTop = EditorBridge.provideContentPaddingTop();
var paddingBottom = EditorBridge.provideContentPaddingBottom();
var paddingLeft = EditorBridge.provideContentPaddingLeft();
var paddingRight = EditorBridge.provideContentPaddingRight();

setContentPaddingTop(paddingTop);
setContentPaddingBottom(paddingBottom);
setContentPaddingLeft(paddingLeft);
setContentPaddingRight(paddingRight);

var contentHeight = EditorBridge.provideContentHeight();
contentHeight = contentHeight - paddingTop - paddingBottom;
setContentHeight(contentHeight);

var placeholder = EditorBridge.providePlaceholder();
setPlaceholder(placeholder);

var content = EditorBridge.provideContent();
$('#editor').append(content);

setupImage(false);
setupEditor();
reformatLinks();

$(document).ready(function() {
	$('a').click(function(event) {
		event.stopPropagation();
	});

	$('body').click(function(event) {
		var tag = event.target.tagName.toLowerCase();
		if (tag != 'a' && tag != 'img') {
			EditorBridge.onClickBody();
		}
	});

	autoLayoutLinkBox();
	autoLayoutVideoBox();
	setContentVisible(true);
	// 手动调用 startIntervalSave();
	EditorBridge.onDocumentReady();
});